<template>
  <el-dialog v-model="model" @close="closedDialog">
    <el-form ref="formRef" :model="form" :rules="rules">
      <el-row>
        <el-col :span="24">
          <el-form-item prop="name">
            <el-input
              v-model="form.name"
              :placeholder="$t('forgot.name')"
              show-word-limit
              clearable
              autocomplete="off"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="captchaCode">
            <graphic-validate
              v-model:captcha-id="form.captchaId"
              v-model:captcha-code="form.captchaCode"
              :placeholder="$t('forgot.captchaCodeRequired')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="validCode">
            <name-validate
              :name="form.name"
              :validate-field="['name', 'captchaCode']"
              :captcha-id="form.captchaId"
              :captcha-code="form.captchaCode"
              :form-ref="formRef"
              :placeholder="$t('forgot.validCode')"
              v-model="form.validCode"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="pwd">
            <el-input
              v-model="form.pwd"
              :placeholder="$t('forgot.pwd')"
              type="password"
              show-password
              show-word-limit
              clearable
              autocomplete="new-password"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="repeatPwd">
            <el-input
              v-model="form.repeatPwd"
              :placeholder="$t('forgot.repeatPwd')"
              type="password"
              show-password
              show-word-limit
              clearable
              autocomplete="new-password"
            />
          </el-form-item>
        </el-col>
        <el-button
          :loading="loading"
          type="primary"
          class="w-full"
          @click.prevent="handleForgot"
        >
          {{ $t("forgot.forgot") }}
        </el-button>
      </el-row>
    </el-form>
  </el-dialog>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import { useI18n } from "vue-i18n";
import { ElMessage } from "element-plus";

import { validateEmail, validatePhoneNumber } from "@/utils/validation_utils";
import { forgotPhoneEmail } from "@/api/auth";

import type { FormInstance, FormRules } from "element-plus";
import type { ForgotPhoneEmailReq } from "@/api/auth/types";

const { t } = useI18n();
// 弹框控制
const model = defineModel<boolean>();
// 关闭弹框
function closedDialog() {
  if (model.value) {
    model.value = false;
  }
}

const formRef = ref<FormInstance>();
const form = ref<ForgotPhoneEmailReq>({
  // 用于检测重复请求的唯一字符串ID
  requestId: Math.random() * 10 + "",
  // 手机号/邮箱
  name: "",
  // 手机号/邮箱的验证码
  validCode: "",
  // 密码
  pwd: "",
  // 确认密码
  repeatPwd: "",
  directoryId: "",
  clientId: "",
});

// 手机号校验
const mobileValidate = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error(t("forgot.nameRequired")));
  } else {
    if (!validatePhoneNumber(value) && !validateEmail(value)) {
      callback(new Error(t("forgot.phoneOrEmailError")));
    } else {
      callback();
    }
  }
};

// 密码校验
const pwdValidate = (rule: any, value: any, callback: any) => {
  const ISPWD =
    /^(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%?^&*,\._\+(){}])[0-9a-zA-Z!@#$%?^&*,\\._\+(){}]{8,20}$/; // eslint-disable-line
  if (value === "") {
    callback(new Error(t("forgot.pwdRequired")));
  } else if (!ISPWD.test(value)) {
    callback(new Error(t("forgot.pwdRules")));
  } else {
    callback();
  }
};

// 确认密码校验
const confirmPwdValidate = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error(t("forgot.repeatPwdRequired")));
  } else if (value !== form.value.pwd) {
    callback(new Error(t("forgot.comparePwd")));
  } else {
    callback();
  }
};

const rules = reactive<FormRules<ForgotPhoneEmailReq>>({
  name: [
    {
      required: true,
      validator: mobileValidate,
      trigger: "blur",
    },
  ],
  captchaCode: [
    {
      required: true,
      message: t("forgot.captchaCodeRequired"),
      trigger: "blur",
    },
  ],
  validCode: [
    {
      required: true,
      message: t("forgot.validCodeRequired"),
      trigger: "blur",
    },
  ],
  pwd: [{ required: true, validator: pwdValidate, trigger: "blur" }],
  repeatPwd: [
    { required: true, validator: confirmPwdValidate, trigger: "blur" },
  ],
});

const loading = ref(false);
function handleForgot() {
  formRef.value?.validate((valid: boolean) => {
    if (!valid) return;
    const formData = {
      name: form.value.name,
      validCode: form.value.validCode,
      pwd: form.value.pwd,
      repeatPwd: form.value.repeatPwd,
      requestId: form.value.requestId,
    };
    forgotPhoneEmail(formData).then((res) => {
      if (res.status === 200) {
        closedDialog();
        ElMessage.success(t("forgot.forgotSuccess"));
      }
    });
  });
}
</script>
<style lang="scss" scoped></style>
